package maiaclient;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author stijn
 * @date 2007-2008
 */
public class PassEncryptor {

    /**
     * Encrypts a given cleartext password by the SHA algorithm.
     * @param clearTextPassword
     * @return hash string
     * @throws java.security.NoSuchAlgorithmException
     */
    public static String getSHAEncodedPassword(String clearTextPassword) {
        String hash = null;
        
        try {

            MessageDigest md = MessageDigest.getInstance("SHA");
            md.reset();
            md.update(clearTextPassword.getBytes());

            byte[] rawBytes = md.digest();

            hash = byteArrayToHexString(rawBytes);

            
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(PassEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        }
        return hash;
    }
    
    
    /**
     * Converts a byte array to HexString.
     * @param b
     * @return hex string
     */
    public static String byteArrayToHexString(byte[] b){
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (int i = 0; i < b.length; i++){
      int v = b[i] & 0xff;
      if (v < 16) {
        sb.append('0');
      }
      sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
}

    /**
     * Converts a HexString to a byte array.
     * @param s
     * @return byte array
     */
    public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++){
      int index = i * 2;
      int v = Integer.parseInt(s.substring(index, index + 2), 16);
      b[i] = (byte)v;
    }
    return b;
  }
}
